<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <input type="text" id="txt">
  <input type="button" id="btn" value="搜索">
  <table border="1" width="600">
    <thead>
      <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
      </tr>
    </thead>
    <tbody id="tbody">
      <!-- <tr>
        <td>1</td>
        <td>zs</td>
        <td>20</td>
        <td>男</td>
      </tr> -->
    </tbody>
  </table>
  <script>
    //1.在搜索按钮上注册点击事件
    document.getElementById('btn').onclick = function(){
      //2.事件函数中
      //  1)获取搜索的关键字
      var valuekey = document.getElementById('txt').value;
      console.log(valuekey);
      //  2)发送 Ajax 请求并将关键词一起发送给后端
      var xhr = new XMLHttpRequest();
      xhr.open('get','/api/searchStudent?name='+ valuekey);
      xhr.send();
      //  3)使用 onload 事件接收后端返回的数据并显示到tbody标签中
      xhr.onload = function(){
        console.log(xhr.responseText);
        // ① 将字符串转回数组(使用JSON.parse()方法)
        var result = JSON.parse(xhr.responseText);
        console.log(result);

        //② 循环遍历数组，读取出每个数据，拼接成一个tr-td字符串
        var str = '';
        for(var i = 0; i <result.length; i++){
          str += 
            ' <tr>\
              <td>'+result[i].id+'</td>\
              <td>'+result[i].name+'</td>\
              <td>'+result[i].age+'</td>\
              <td>'+result[i].gender+'</td>\
            </tr>'
        };
        console.log(str);
        document.getElementById('tbody').innerHTML = str;
      };
    };
  </script>
</body>
</html>